import echarts from 'echarts'
import $http from '../utils/http.js'
import { Notification } from 'atelement'
import $download from '../utils/download.js'
import { getmakeStringDes } from './analyze/utils/makeString'

const riskeventData = 'riskevents/riskData'
const riskeventAdd = 'riskEvents/riskData/add'
const riskverify = 'riskEvents/riskverify'
const riskEventssort = 'riskEvents/sotr'
const riskEventsfilters = 'riskEvents/filters'
const riskEventchValue = 'riskEvents/changeSearchValue'
const riskEventChange = 'riskEvents/paginationChange'
const DelectRisk = 'riskEvents/delect'
const riskEventsDerailInitil = 'riskEventsDerails/InitialValue'
const riskguiru = 'riskEvents/guiru'
const risktijiao = 'riskEvents/tijiao'
const riskguiruone = 'riskEvents/guiruone'
const riskupdate = 'riskEvents/riskData/update'
const riskEventsDerailalarmlog = 'riskEventsDerails/alarmlog'
const riskEventsDerailsdownload = 'riskEventsDerails/download'
const filtersriskentid = 'riskEvents/filters/riskentid'
const filtersriskentidzero = 'riskevents/riskData/riskidzeo'
const clear = 'riskevents/clear'
export default{
  state: {
    riskData: [],
    tableDataone: [],
    risk_sum: {},
    update: {
      riskname: '',
      risktype: '',
      risklevel: '',
      risksolution: '',
      riskdescribe: '',
      remark: ''
    },
    echarts: {
      type: ['新兴', '高危', '流行', '攻击类'],
      color: ['#ffd140', '#2495ef', '#53cb7b', '#ff9933'],
      data: [ { value: 0, name: '新兴' }, { value: 0, name: '高危' }, { value: 0, name: '流行' }, { value: 0, name: '攻击类' } ]
    },
    riskEventsSubmit: {
      pagination: {
        total: 0,
        current: 1, // 当前页码
        pageSize: 20 // 当前页显示的数据条数
      },
      search: {
        value: '' // 需要模糊搜索的值（搜索框）
      },
      sorter: {
        field: 'ar_time', // 排序的字段
        order: 'descend' // 升序还是降序
      },
      filters: {
        // 需要被过滤的字段
        arisk_event_id: [],
        arisk_event_level: [],
        arisk_event_type: [],
        ais_commit: [],
        aearly_warn: []
      },
      dict: {
        // 额外参数
      }
    }
  },
  actions: {
    // 风险事项获取表格数据
    [riskeventData] ({ commit, state }) {
      $http.option('/api/riskevents/getdata', state.riskEventsSubmit)
        .then(({ status, msg, data } = {}) => {
          if (status === 'success') {
            commit(riskeventData, data)
          } else if (status === 'fail') {
            Notification.warning(msg)
          }
        })
    },
    // 风险事项名字验证
    [riskverify] ({ dispatch, data }, { value, DataValidation, eventid = 0 }) {
      $http.post('/api/riskEvents/riskverify', { value: value, eventid: eventid })
        .then(({ status, msg, data } = {}) => {
          dispatch(riskeventData)
          DataValidation(status)
        })
    },
    // 新增风险事项
    [riskeventAdd] ({ dispatch, state }, { data }) {
      $http.post('/api/riskEvents/add', data)
        .then(({ status, msg, data } = {}) => {
          if (status === 'success') {
            dispatch(riskeventData)
            Notification.success({
              title: '增加成功',
              message: msg
            })
          } else {
            Notification.error({
              title: '增加失败',
              message: msg
            })
          }
        })
    },
    // 修改风险事项
    [riskupdate] ({ dispatch, state }, { data, resData }) {
      $http.post('/api/riskEvents/riskupdate', data)
        .then(({ status, msg, data } = {}) => {
          if (status === 'success') {
            dispatch(riskEventsDerailInitil, { data: { id: resData.id }, fun: resData.fun })
            // location .reload()
            Notification.success({
              title: '修改成功',
              message: msg
            })
          } else {
            Notification.error({
              title: '修改失败',
              message: msg
            })
          }
        })
    },
    // 风险事项详情附录 riskEventsDerailalarmlog
    [riskEventsDerailalarmlog] ({ commit, dispatch }, { data, fun }) {
      $http.post('/api/riskEvents/Derails/larmlog', data)
        .then(({ status, msg, data } = {}) => {
          if (status === 'success') {
            for (let index in data.dataSource.warninfos) {
              let logs = data.dataSource.warninfos[index].logs
              for (let logIndex in logs) {
                let log = logs[logIndex]
                log.describes = getmakeStringDes(log)
                log.log_type_cn = getmakeStringDes(log, 'name')
              }
            }
            fun('appendix', data['dataSource'])
          } else if (status === 'fail') {
            Notification.error({
              title: '加载失败',
              message: msg
            })
          }
        })
    },
    // 风险事项筛选值
    [riskEventsfilters] ({ commit, dispatch }, filters) {
      commit(riskEventsfilters, filters)
      dispatch(riskeventData)
    },
    // 风险详情排序值
    [riskEventssort] ({ commit, dispatch }, { key, value }) {
      commit(riskEventssort, { key, value })
      dispatch(riskeventData)
    },
    // 风险管理改变搜索值
    [riskEventchValue] ({ commit, dispatch }, value) {
      commit(riskEventchValue, value)
      dispatch(riskeventData)
    },
    // 风险管理改变页码值
    [riskEventChange] ({ commit, dispatch }, value) {
      commit(riskEventChange, value)
      dispatch(riskeventData)
    },
    // 删除风险事项
    [DelectRisk] ({ dispatch }, value) {
      $http.post('/api/riskEvents/delete', value)
        .then(({ status, msg } = {}) => {
          if (status === 'success') {
            dispatch(riskeventData)
            // dispatch(riskDataechatts)
            Notification.success({
              title: '删除成功',
              message: msg
            })
          } else if (status === 'fail') {
            Notification.error({
              title: '删除失败',
              message: msg
            })
          }
        })
    },
    // 风险详情通过id获取数据接口
    [riskEventsDerailInitil] ({ commit, dispatch }, { data, fun }) {
      $http.post('/api/riskEvents/Derails/getInitil', data)
        .then(({ status, msg, data } = {}) => {
          if (status === 'success') {
            fun('detaildata', data.dataSource)
            fun('correlation', data.correlation)
            fun('TimeLineData', data.operate)
          } else if (status === 'fail') {
            Notification.error({
              title: '加载失败',
              message: msg
            })
          }
        })
    },
    // 风险事项归入信息查询
    [riskguiru] ({ commit, dispatch }, value) {
      $http.post('/api/riskEvents/guiru', value)
        .then(({ status, msg, data } = {}) => {
          if (status === 'success') {
            commit(riskguiru, data)
          } else if (status === 'fail') {
            Notification.error({
              title: '删除失败',
              message: msg
            })
          }
        })
    },
    // 风险事项提交处置
    [risktijiao] ({ dispatch }, { data, fun, eventId }) {
      $http.post('/api/riskEvents/risktijiao', data)
        .then(({ status, msg } = {}) => {
          if (status === 'success') {
            dispatch(riskEventsDerailInitil, { data: eventId, fun: fun })
            Notification.success({
              title: '提交成功',
              message: msg
            })
          } else if (status === 'fail') {
            Notification.error({
              title: '提交失败',
              message: msg
            })
          }
        })
    },
    // 选择相应的风险事项信息归入
    [riskguiruone] ({ dispatch }, { data, ariskEventId }) {
      $http.option('/api/riskEvent/guiruone', data)
        .then(({ status, msg }) => {
          if (status === 'success') {
            dispatch(riskguiru, { ariskEventId })
            dispatch(riskeventData)
            Notification.success({
              title: '归入成功',
              message: msg
            })
          } else if (status === 'fail') {
            Notification.error({
              title: '归入失败',
              message: msg
            })
          }
        })
    },
    // 根据依据路径下载相对应的文件
    [riskEventsDerailsdownload] ({ commit, dispatch }, { data }) {
      $download.post('/api/riskwarning/download', data)
    },
    // 风险管理跳转页面
    [filtersriskentid] ({ commit, dispatch }, value) {
      commit(filtersriskentid, value)
      dispatch(riskeventData)
    },
    // id重置
    [filtersriskentidzero] ({ commit, dispatch }) {
      commit(filtersriskentidzero)
      dispatch(riskeventData)
    }
  },
  mutations: {
    [riskeventData] (state, data) {
      state.riskData = data.dataSource
      state.risk_sum = data.sumrisk
      // 对返回分数据进行分类并整理
      for (let x = 0; x < data.echarts.length; x++) {
        for (let i = 0; i < state.echarts['type'].length; i++) {
          if (data.echarts[x]['risk_event_type'] === state.echarts['type'][i]) {
            state.echarts['data'][i]['value'] = data.echarts[x]['count']
          }
        }
      }
      if (document.getElementById('typemap')) {
        let m = document.getElementById('typemap')
        let myChart = echarts.init(m)
        let option = {
          title: {
            text: '风险事项类型分布情况',
            x: 'left',
            left: 10,
            top: 15,
            textStyle: {
              fontSize: 12
            }
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a}{b}: {c}'
          },
          legend: {
            orient: 'vertical',
            icon: 'circle',
            left: '230',
            top: '50',
            itemWidth: 7,
            itemHeight: 7,
            formatter: function (name) {
              for (let i = 0; i < state.echarts['data'].length; i++) {
                if (state.echarts['data'][i]['name'] === name) {
                  return name + ': ' + state.echarts['data'][i]['value']
                }
              }
            }
          },
          series: [
            {
              name: '',
              type: 'pie',
              radius: ['40%', '60%'], // 内圆和外圆
              center: ['30%', '60%'], // 位置
              avoidLabelOverlap: false,
              label: {
                normal: {
                  show: false,
                  formatter: '{c}',
                  position: 'center'
                },
                emphasis: {
                  show: true,
                  color: '#5c6781',
                  textStyle: {
                    fontSize: '16'
                  }
                }
              },
              labelLine: {
                normal: {
                  show: false
                }
              },
              data: state.echarts['data']
            }
          ],
          color: ['#ffd140', '#2495ef', '#53cb7b', '#ff9933']
        }
        myChart.setOption(option)
      }
      if (document.getElementById('typemapone')) {
        let m = document.getElementById('typemapone')
        let myChart = echarts.init(m)
        let option = {
          title: {
            text: '风险事项等级分布情况',
            x: 'left',
            left: 10,
            top: 15,
            textStyle: {
              fontSize: 12
            }
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a}{b}: {c}'
          },
          legend: {
            orient: 'vertical',
            icon: 'circle',
            left: '230',
            top: '50',
            itemWidth: 7,
            itemHeight: 7,
            formatter: function (name) {
              // 遍历json数组
              for (let key in data.echartsone) {
                if (key === name) {
                  return name + ': ' + data.echartsone[key]
                }
              }
            }
          },
          series: [
            {
              name: '',
              type: 'pie',
              radius: ['40%', '60%'], // 内圆和外圆
              center: ['30%', '60%'], // 位置
              avoidLabelOverlap: false,
              label: {
                normal: {
                  show: false,
                  formatter: '{c}',
                  position: 'center'
                },
                emphasis: {
                  show: true,
                  color: '#5c6781',
                  textStyle: {
                    fontSize: '16'
                  }
                }
              },
              labelLine: {
                normal: {
                  show: false
                }
              },
              data: [ { value: data.echartsone['一般'], name: '一般' }, { value: data.echartsone['较大'], name: '较大' }, { value: data.echartsone['重大'], name: '重大' }, { value: data.echartsone['特大'], name: '特大' } ]
            }
          ],
          color: ['RGB(255,201,51)', 'RGB(255,152,53)', 'RGB(253,103,53)', 'RGB(255,51,52)']
        }
        myChart.setOption(option)
      }

      let i = []
      let x = []
      let y = []
      data.timeecharts.forEach(function (val, index) {
        i.push(val.r_time)
        x.push(val.all_risk_cnt)
        y.push(val.handle_risk_cnt)
      })

      if (document.getElementById('bigpolang')) {
        let m = document.getElementById('bigpolang')
        let myChart = echarts.init(m)
        let option = {
          xAxis: {
            type: 'category',
            data: i,
            boundaryGap: false,
            axisTick: {
              show: false
            },
            axisLabel: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: '#1f92ef'
              }
            }
          },
          yAxis: {
            type: 'value',
            show: false
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'none',
              label: {
                backgroundColor: '#6a7985'
              }
            },
            textStyle: {
              color: '#fff',
              fontSize: 12,
              fontFamily: 'SimSun'
            }
          },
          series: [
            {
              name: '风险事项总数',
              type: 'line',
              smooth: true,
              areaStyle: {
                color: '#e8f4fd',
                opacity: 1
              },
              lineStyle: {
                width: 1,
                color: '#e8f4fd'
              },
              itemStyle: {
                color: '#e8f4fd'
              },
              symbol: 'none',
              data: x
            },
            {
              name: '已提交预警数',
              type: 'line',
              smooth: true,
              areaStyle: {
                color: '#1f92ef',
                opacity: 1
              },
              lineStyle: {
                width: 1,
                color: '#1f92ef'
              },
              itemStyle: {
                color: '#1f92ef'
              },
              symbol: 'none',
              data: y
            }
          ],
          grid: {
            top: 5,
            bottom: 1,
            left: 0,
            right: 0
          }
        }
        myChart.setOption(option)
      }
    },
    // 风险事项筛选值
    [riskEventsfilters] (state, filters) {
      if (filters.arisk_event_level !== undefined) {
        state.riskEventsSubmit.filters.arisk_event_level = filters.arisk_event_level
      }
      if (filters.aearly_warn !== undefined) {
        state.riskEventsSubmit.filters.aearly_warn = filters.aearly_warn
      }
      if (filters.arisk_event_type !== undefined) {
        state.riskEventsSubmit.filters.arisk_event_type = filters.arisk_event_type
      }
      if (filters.ais_commit !== undefined) {
        state.riskEventsSubmit.filters.ais_commit = filters.ais_commit
      }
    },
    // 风险事项排序
    [riskEventssort] (state, { key, value }) {
      state.riskEventsSubmit.sorter.field = key
      state.riskEventsSubmit.sorter.order = value
    },
    // 风险事项搜索
    [riskEventchValue] (state, value) {
      if (value.type) {
        state.riskEventsSubmit.search.value = value.search
      } else {
        state.riskEventsSubmit.dict.userFlag = value.userFlag
      }
    },
    // 将前端的页码值和显示数给state
    [riskEventChange] (state, value) {
      if (value.size) {
        state.riskEventsSubmit.pagination.pageSize = value.size
      }
      if (value.current) {
        state.riskEventsSubmit.pagination.current = value.current
      }
    },
    // 风险事项归入信息获取
    [riskguiru] (state, data) {
      for (let index in data.dataSource) {
        let log = data.dataSource[index]
        log.describes = getmakeStringDes(log)
        log.log_type_cn = getmakeStringDes(log, 'name')
      }
      state.tableDataone = data.dataSource
    },
    [filtersriskentid] (state, value) {
      state.riskEventsSubmit.filters.arisk_event_id[0] = value.riskEeventid
    },
    [filtersriskentidzero] (state) {
      state.riskEventsSubmit.filters.arisk_event_id = []
    },
    [clear] (state) {
      state.riskEventsSubmit = {
        pagination: {
          total: 0,
          current: 1, // 当前页码
          pageSize: 20 // 当前页显示的数据条数
        },
        search: {
          value: '' // 需要模糊搜索的值（搜索框）
        },
        sorter: {
          field: 'ar_time', // 排序的字段
          order: 'descend' // 升序还是降序
        },
        filters: {
          // 需要被过滤的字段
          arisk_event_id: [],
          arisk_event_level: [],
          arisk_event_type: [],
          ais_commit: [],
          aearly_warn: []
        },
        dict: {
          // 额外参数
        }
      }
    }
  }
}
